package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import com.itheima.reggie.utils.AlipayUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;

@Controller
@Slf4j
public class AlipayController {
   @Autowired
   private ShoppingCartService shoppingCartService;

    private AlipayUtils alipayUtils;
    @Autowired
    public void setAlipayUtils(AlipayUtils alipayUtils) {
        this.alipayUtils = alipayUtils;
    }



    @GetMapping("/")
    public String index()
    {
        return "index";
    }


    @GetMapping("/templates/pays")
    public String create(Orders orders, Model model) {
        // 获取用户id
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> lqwShoppingCart = new LambdaQueryWrapper<>();
        lqwShoppingCart.eq(ShoppingCart::getUserId,userId);

        //获取菜品
        List<ShoppingCart> list = shoppingCartService.list(lqwShoppingCart);


        /*int number = one.getNumber();
        //价格
        String s = String.valueOf(one.getAmount().doubleValue()*number);*/

        double price=0;
        for (ShoppingCart shoppingCart : list) {
            int number=shoppingCart.getNumber();
            double v = shoppingCart.getAmount().doubleValue() * number;
            price+=v;
        }
        String s = String.valueOf(price);


        // 生成订单号
        String id = String.valueOf(IdWorker.getId());
        String pay = alipayUtils.pay(id, s, "1");
        model.addAttribute("form", pay);
        return "pay";
    }

    @GetMapping("/return")
    public String returnNotice(String out_trade_no, Model model) {
        System.err.println("返回界面");
        String query = alipayUtils.query(out_trade_no);
        model.addAttribute("query", query);
        return "query";
    }




}
